﻿using System;
using System.Data.SQLite;
using System.IO;
using EzDesk.DesktopClient.Model;
using EzDesk.Generic;

namespace EzDesk.DesktopClient.Storage
{
    public class ClientDbStorage
    {
        private const string RelatedPath = "user\\data";
        private const string StoreType = "database";
        private const string TemplateDatabase = "datatemplate\\EzDesktopClientDb.db";

        public static void ClearLocalDatabase()
        {
            var folderPath = GetUserPath();
            if (Directory.Exists(folderPath))
            {
                try
                {
                    Directory.Delete(folderPath,true);
                }
                catch (Exception exp)
                {
                    LogEx.ERROR("ClearLocalDatabase",exp.Message,exp);
                }
                
            }
        }

        public static EzDesktopClientDb GetDataContext(string name)
        {
            EzDesktopClientDb dataContext = null;
            dataContext = new EzDesktopClientDb(new SQLiteConnection(GetConnectionString(name)));
            return dataContext;
        }

        private static string GetConnectionString(string name)
        {
            string databaseUrl = GetFilePath(name, StoreType);
            if (!File.Exists(databaseUrl))
            {
                File.Copy(TemplateDataBaseFile(), databaseUrl, false);
            }
            return string.Format("Data Source={0}", databaseUrl);
        }
        private static string GetFilePath(string name, string storeType=StoreType)
        {
            string folderPath = GetDatabaseFolderPath(storeType);
            if (!Directory.Exists(folderPath))
                Directory.CreateDirectory(folderPath);
            return Path.Combine(folderPath, name);
        }

        private static string GetDatabaseFolderPath(string storeType=StoreType)
        {
            string userPath = GetUserPath();
            return Path.Combine(userPath,storeType);
        }

        private static string GetUserPath()
        {
            return Path.Combine(PathHelp.CurrentPath, RelatedPath);
        }

        private static string TemplateDataBaseFile()
        {
            return Path.Combine(PathHelp.CurrentPath, TemplateDatabase);
        }
    }
}
